﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;

using CE.User;
using CE.Global;
using CE.Provider;
using CE.Image;

public partial class Provider_PersonalAccident_ProviderPolicyWriting : System.Web.UI.Page
{
    string PageName = "CXPA";
    string SubPageName = "CXPAPLWRT";
    public static Int64 _providerdocumentid = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] == null || Session[CE.Global.General.ProviderCompanyId] == null)
        {
            Response.Redirect("~/Provider/ProviderSecureLogin.aspx");
        }
        CheckMainPageAccess();
        CheckSubPageAccess();

        if (!IsPostBack)
        {
            ClearProcess();
            if (Request.Params["PWID"] != null)
            {
                Int32 _policydocid;
                if (Int32.TryParse(Request.Params["PWID"].ToString(), out _policydocid))
                {
                    ShowPolicy(_policydocid);
                }
            }
        }
    }

    protected void ibtSubmit_Click(object sender, ImageClickEventArgs e)
    {
        if (Page.IsValid)
        {
            if (fleUpload.PostedFile != null)
            {
                HttpPostedFile myFile = fleUpload.PostedFile;
                int fileSize = myFile.ContentLength;
                FileInfo fInfo = new FileInfo(myFile.FileName);

                if (fileSize > 0 && (fileSize / 1024) < 4096)
                {
                    if (CheckExtension(fInfo.Extension) == true)
                    {

                        MyImage myImage = new MyImage();
                        // Allocate a buffer for reading of the file
                        byte[] myData = new byte[fileSize];

                        // Read uploaded file from the Stream
                        myFile.InputStream.Read(myData, 0, fileSize);

                        string providerFolder = "";
                        if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("LibertyProviderCompanyId"))
                            providerFolder = "Liberty/PA/";
                        else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("EtiqaProviderCompanyId"))
                            providerFolder = "Etiqa/PA/";
                        else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("HSBCProviderCompanyId"))
                            providerFolder = "HSBC/PA/";
                        else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("ChinaProviderCompanyId"))
                            providerFolder = "ChinaTaiping/PA/";
                        else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("EQProviderCompanyId"))
                            providerFolder = "EQ/PA/";

                        string strFilename = Path.GetFileName(myFile.FileName);
                        string _strDocPath = CE.Configuration.MyConfigurationManager.GetAppSettingValue("UploadDocPath");
                        string uploadPath = Server.MapPath(_strDocPath + providerFolder + strFilename);

                        //check if directory exists
                        string directoryToUpload = uploadPath;


                        if (!Directory.Exists(directoryToUpload))
                        {
                            //creates the folder
                            string pathtocreate = Server.MapPath(_strDocPath + providerFolder.Remove(providerFolder.Length - 1, 1));
                            Directory.CreateDirectory(pathtocreate);
                        }

                        if (!File.Exists(uploadPath))
                        {

                            // Write data into a file
                            myImage.WriteToFile(uploadPath, ref myData);

                            ProviderPolicyDocument _policydoc = new ProviderPolicyDocument();
                            ProviderPolicyDocumentDB _policydocdb = new ProviderPolicyDocumentDB();

                            _policydoc.DocumentId = Convert.ToInt64(lblProviderPAPolicyId.Text);
                            _policydoc.DocumentName = txtPolicyDoc.Text.Trim();
                            _policydoc.Description = txtPolicyDescription.Text.Trim();
                            _policydoc.ForWhat = "PA";
                            _policydoc.SizeKB = fileSize;
                            _policydoc.UploadPath = _strDocPath + providerFolder + strFilename;
                            _policydoc.ProviderCompanyId = Convert.ToInt64(Session[CE.Global.General.ProviderCompanyId].ToString());
                            _policydoc.RefCEUserId = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());
                            _policydoc.Status = Convert.ToBoolean(chkStatus.Checked.ToString());
                            _policydoc.DocumentId = _policydocdb.Insert(_policydoc);

                            if (_policydoc.DocumentId > 0)
                            {
                                ClearProcess();
                                lblMessage.Text = "Saved successfully!";
                                Response.Redirect("ViewProviderPolicyWriting.aspx");
                            }
                            else
                            {
                                lblMessage.Text = "Saving failed!";
                            }
                        }
                        else
                        {
                            lblMessage.Text = "File already exists.";
                        }

                    }
                    else
                    {
                        lblMessage.Text = "Only PDF Files can be attached.";
                    }
                }
                else
                {
                    lblMessage.Text = "File size should be under 4 MB.";
                }
            }
        }
    }

    protected void btnNew_Click(object sender, ImageClickEventArgs e)
    {
        ClearProcess();
    }

    protected void ibtBack_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("ViewProviderPolicyWriting.aspx");
    }

    private static bool CheckExtension(string Extension)
    {
        //string[] extList = { ".doc", ".pdf", ".docx", ".txt", ".rtf", ".ppt", ".pptx", ".xls" };
        string[] extList = { ".pdf" };
        bool isInList = false;
        for (int i = 0; i < extList.Length; i++)
        {
            if (Extension == extList[i])
            {
                isInList = true;
                break;
            }
        }
        return isInList;
    }

    private void ShowPolicy(Int64 DocumentId)
    {
        ProviderPolicyDocument _policydoc = new ProviderPolicyDocument();
        ProviderPolicyDocumentDB _policydocdb = new ProviderPolicyDocumentDB();

        _policydoc = _policydocdb.GetProviderPolicyDocument(DocumentId);

        if (_policydoc != null)
        {
            lblProviderPAPolicyId.Text = _policydoc.DocumentId.ToString();
            txtPolicyDoc.Text = _policydoc.DocumentName;
            txtPolicyDescription.Text = _policydoc.Description;
            lnkpolicydoc.NavigateUrl = _policydoc.UploadPath.ToString();
            lnkpolicydoc.Text = _policydoc.DocumentName;
            chkStatus.Checked = Convert.ToBoolean(_policydoc.Status);
        }

    }

    public void ClearProcess()
    {
        _providerdocumentid = 0;
        lblProviderPAPolicyId.Text = "0";
        txtPolicyDoc.Text = "";
        txtPolicyDescription.Text = "";
        lnkpolicydoc.Text = "";
        chkStatus.Checked = true;
        lblMessage.Text = "";

    }

    private void CheckMainPageAccess()
    {
        Int64 PageAccess = General.GetProviderMainPageAccess(Convert.ToInt64(Session[General.ProviderCompanyId].ToString()),
                                                        Convert.ToInt64(Session[General.UserId].ToString()), PageName);
        if (PageAccess == 0)
        {
            //Response.Redirect("~/Provider/UserMessage.aspx?errorcode=2000");
            Response.Redirect("~/Provider/UserMessage.aspx?mt=UM&ec=2000");
        }
    }

    private void CheckSubPageAccess()
    {
        Int64 PageAccess = General.GetProviderSubPageAccess(Convert.ToInt64(Session[General.ProviderCompanyId].ToString()),
                                                        Convert.ToInt64(Session[General.UserId].ToString()), SubPageName);
        if (PageAccess == 0)
        {
            //Response.Redirect("~/Provider/UserMessage.aspx?errorcode=2000");
            Response.Redirect("~/Provider/UserMessage.aspx?mt=UM&ec=2000");
        }
        else if (PageAccess == 100)
        {
            ibtSubmit.Enabled = false;
            btnNew.Enabled = false;
            //btnDelete.Enabled = false;
        }
        else if (PageAccess == 200)
        {
            ibtSubmit.Enabled = true;
            btnNew.Enabled = true;
            //btnDelete.Enabled = false;
        }
        else if (PageAccess == 300)
        {
            ibtSubmit.Enabled = true;
            btnNew.Enabled = true;
            //btnDelete.Enabled = true;
        }
    }

}
